package com.cube.share.spi.service;

import lombok.var;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author cube.li
 * @date 2021/7/7 22:30
 * @description
 */
@Component
public class FileServiceFactory implements InitializingBean {

    @Value("${file.service.type:OSS}")
    private String fileServiceType;

    private FileService fileService;

    private Map<String, FileService> fileServiceMap = new HashMap<>();

    public Object upload(InputStream inputStream) {
        return fileService.upload(inputStream);
    }

    public void download(String fileId, String path) {
        fileService.download(fileId, path);
    }

    @Override
    public void afterPropertiesSet() {
        var serviceLoader = ServiceLoader.load(FileService.class);
        for (FileService customFileService : serviceLoader) {
            System.out.println(customFileService.getClass().getName());
            fileServiceMap.put(customFileService.getType(), customFileService);
        }
        fileService = fileServiceMap.get(fileServiceType);
    }
}
